package com.learn.thread;

public class TestUnSafeThreadSynchronized {
    public static void main(String[] args) {
        TicketOffice ticketOffice = new TicketOffice();
        new Thread(ticketOffice, "小明").start();
        new Thread(ticketOffice, "小红").start();
        new Thread(ticketOffice, "黄牛").start();
    }
}

//synchronized 锁的是当前对象，因为每个对象都有一把锁，，
//synchronized 修饰到方法上就成了同步方法
class TicketOffice implements Runnable {
    private int ticketNum = 10;
    private Boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            buyTicket();
        }
    }

    private synchronized void buyTicket() {
        if (ticketNum == 0) {
            flag = false;
        } else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "抢到了第" + ticketNum + "张票");
            ticketNum--;
        }
    }
}